package cn.minsh.lims.eoms.modules.job.task;

import cn.minsh.lims.eoms.modules.app.entity.UserInspectionPlanEntity;
import cn.minsh.lims.eoms.modules.app.entity.UserInspectionPlanScopeEntity;
import cn.minsh.lims.eoms.modules.app.enums.PlanResultEnum;
import cn.minsh.lims.eoms.modules.app.enums.PlanStatusEnum;
import cn.minsh.lims.eoms.modules.app.service.UserInspectionPlanScopeService;
import cn.minsh.lims.eoms.modules.app.service.UserInspectionPlanService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 检查用户巡检逾期
 * @author Administrator
 */
@Component("checkUserInspectionPlanOverdueTask")
public class CheckUserInspectionPlanOverdueTask implements ITask{

    @Autowired
    private UserInspectionPlanService userInspectionPlanService ;
    @Autowired
    private UserInspectionPlanScopeService userInspectionPlanScopeService ;

    @Override
    public void run(String params) {
        //查询出用户结束时间早于当前时间，并且未关闭的巡检计划
        QueryWrapper<UserInspectionPlanEntity> wrapper = new QueryWrapper<>() ;
        wrapper.ne("status", PlanStatusEnum.OVER.getCode()) ;
        wrapper.le("plan_end_time",new Date()) ;
        List<UserInspectionPlanEntity> list = userInspectionPlanService.list(wrapper) ;

        if (!CollectionUtils.isEmpty(list)){
            List<UserInspectionPlanEntity> updateList = new ArrayList<>() ;
            List<Long> orderIdList = new ArrayList<>() ;
            list.stream().forEach(e->{
                UserInspectionPlanEntity entity = new UserInspectionPlanEntity() ;
                entity.setComplateTime(new Date());
                entity.setResult(PlanResultEnum.OVERDUE.getCode());
                entity.setStatus(PlanStatusEnum.OVER.getCode());
                entity.setComplateTime(new Date());
                entity.setId(e.getId());
                entity.setUpdateBy(-1L);
                entity.setUpdateTime(new Date());
                updateList.add(entity) ;
                orderIdList.add(entity.getId()) ;
            });
            userInspectionPlanService.updateBatchById(updateList) ;
            //巡检范围-巡检结果
            UpdateWrapper<UserInspectionPlanScopeEntity> planScopeEntityUpdateWrapper = new UpdateWrapper<>() ;
            planScopeEntityUpdateWrapper.set("result",PlanResultEnum.OVERDUE.getCode()).in("user_inspection_plan_id",orderIdList) ;
            userInspectionPlanScopeService.update(planScopeEntityUpdateWrapper) ;
        }
    }
}
